//
//  LoginViewController.m
//  豆瓣
//
//  Created by dllo on 15/11/21.
//  Copyright (c) 2015年 dllo. All rights reserved.
//

#import "LoginViewController.h"
#import "RegisterViewController.h"
#import <sqlite3.h>

@interface LoginViewController () <UITextFieldDelegate>

@property (nonatomic, retain) UITextField *userField;
@property (nonatomic, retain) UITextField *passwordField;

@end

@implementation LoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    
  /********************************** 登录界面 ***************************************/
    

    self.navigationItem.title = @"用户登录";
    
    // 左上角返回键
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"btn_nav_back.png"] style:UIBarButtonItemStylePlain target:self action:@selector(leftAction)];
    [self.navigationItem.leftBarButtonItem setTintColor:[UIColor blackColor]];
    
    UIImageView *imageV = [[UIImageView alloc] initWithFrame:self.view.frame];
    imageV.image = [UIImage imageNamed:@"bg-568h@2x.png"];
    [self.view addSubview:imageV];
    [imageV release];
  
// 用户名
    UILabel *userLabel = [[UILabel alloc] initWithFrame:CGRectMake(30, 70, 80, 50)];
    userLabel.text = @"用户名 :";
    userLabel.font = [UIFont systemFontOfSize:22];
    [self.view addSubview:userLabel];
    [userLabel release];
    
    self.userField = [[UITextField alloc] initWithFrame:CGRectMake(userLabel.frame.origin.x + userLabel.frame.size.width + 20,  userLabel.frame.origin.y + 8, 230, userLabel.frame.size.height - 17)];
    self.userField.placeholder = @"请输入用户名";
    self.userField.clearButtonMode = UITextFieldViewModeAlways;
    self.userField.borderStyle = UITextBorderStyleRoundedRect;
    self.userField.textAlignment = NSTextAlignmentCenter;
    self.userField.returnKeyType = UIReturnKeyNext;
    self.userField.delegate = self;
    [self.view addSubview:self.userField];
    [self.userField release];
  
// 密码
    UILabel *passwordLabel = [[UILabel alloc] initWithFrame:CGRectMake(userLabel.frame.origin.x, userLabel.frame.origin.y + userLabel.frame.size.height + 6, userLabel.frame.size.width, userLabel.frame.size.height)];
    passwordLabel.text = @"密   码:";
    passwordLabel.font = [UIFont systemFontOfSize:22];
    [self.view addSubview:passwordLabel];
    [passwordLabel release];
    
    self.passwordField = [[UITextField alloc] initWithFrame:CGRectMake(self.userField.frame.origin.x, self.userField.frame.origin.y + self.userField.frame.size.height + 23, self.userField.frame.size.width, self.userField.frame.size.height)];
    self.passwordField.clearButtonMode = UITextFieldViewModeAlways;
    self.passwordField.borderStyle = UITextBorderStyleRoundedRect;
    self.passwordField.textAlignment = NSTextAlignmentCenter;
    self.passwordField.returnKeyType = UIReturnKeyGo;
    self.passwordField.placeholder = @"请输入密码";
    self.passwordField.secureTextEntry = YES;
    self.passwordField.delegate = self;
    [self.view addSubview:self.passwordField];
    [self.passwordField release];
    
    // 登录按钮
    UIButton *loginbutton = [UIButton buttonWithType:UIButtonTypeCustom];
    loginbutton.frame = CGRectMake(65, 320, 75, 75);
    [loginbutton setTitle:@"登录" forState:UIControlStateNormal];
    loginbutton.titleLabel.font = [UIFont systemFontOfSize:28];
    [loginbutton addTarget:self action:@selector(loginAction) forControlEvents:UIControlEventTouchUpInside];
    [loginbutton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [self.view addSubview:loginbutton];
    
    // 注册按钮
    UIButton *registerbutton = [UIButton buttonWithType:UIButtonTypeCustom];
    registerbutton.frame = CGRectMake(218, 320, 75, 75);
    [registerbutton setTitle:@"注册" forState:UIControlStateNormal];
    [registerbutton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    registerbutton.titleLabel.font = [UIFont systemFontOfSize:28];
    [registerbutton addTarget:self action:@selector(registerAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:registerbutton];
    
    UITapGestureRecognizer *tapGR = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)];
    [self.view addGestureRecognizer:tapGR];
    [tapGR release];
    
}

// 登录
- (void)loginAction {
    
    static sqlite3 *DB = nil;
    
    // 打开数据库
    NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,  NSUserDomainMask, YES) lastObject];
    NSString *filePath = [path stringByAppendingPathComponent:@"dataBase.db"];
    sqlite3_open(filePath.UTF8String, &DB);
    
    // 验证
    NSInteger temp = 0;
    NSString *namee = nil;
    NSString *sqlStr = @"SELECT * FROM user";
    sqlite3_stmt *stmt = nil;
    sqlite3_prepare(DB, sqlStr.UTF8String, -1, &stmt, NULL);
    
    while (SQLITE_ROW == sqlite3_step(stmt)) {
        
        const unsigned char *userName = sqlite3_column_text(stmt, 1);
        const unsigned char *userPassword = sqlite3_column_text(stmt, 2);
        NSString *name = [NSString stringWithUTF8String:(const char *)userName];
        NSString *password = [NSString stringWithUTF8String:(const char *)userPassword];
        
        if ([name isEqualToString:self.userField.text] && [password isEqualToString:self.passwordField.text]) {
            
            namee = name;
            temp = 1;
        }
    }
    if (0 == temp) {
        
        UIAlertView *alter = [[UIAlertView alloc] initWithTitle:nil message:@"用户名或密码错误" delegate:nil cancelButtonTitle:@"确认" otherButtonTitles:nil];
        [alter show];
        [alter release];
        [self.userField resignFirstResponder];
        [self.passwordField resignFirstResponder];
        
        // 关闭数据库
        sqlite3_close(DB);
        return;
    }
    else {
        
        // 修改状态为 - 登录(T)
        NSString *sqlStr = [NSString stringWithFormat:@"UPDATE user SET userState = 'T' WHERE userName = '%@'", namee];
        sqlite3_exec(DB, sqlStr.UTF8String, NULL, NULL, NULL);
        // 关闭数据库
        sqlite3_close(DB);

        NSUserDefaults *userLogin = [NSUserDefaults standardUserDefaults];
        [userLogin setObject:@"T" forKey:@"state"];
        [userLogin setObject:namee forKey:@"user"];
        
        [self.delegate changeItem];
        // 登陆成功提示框
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:@"登录成功啦" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
            
            [self.userField resignFirstResponder];
            [self.passwordField resignFirstResponder];
            [self.navigationController popViewControllerAnimated:YES];
        }];
        [alert addAction:cancelAction];
        [self presentViewController:alert animated:YES completion:^{
            
            [self.userField resignFirstResponder];
            [self.passwordField resignFirstResponder];
            
        }];
    }
}

// 跳转到注册界面
- (void)registerAction:(UIButton *)sender {
    
    RegisterViewController *registerVC = [[RegisterViewController alloc] init];
    [self.navigationController pushViewController:registerVC animated:YES];
    [registerVC release];
    
}

// 点击return跳转
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    
    if (textField == self.userField) {
        
        [self.passwordField becomeFirstResponder];
    }
    if (textField == self.passwordField) {
        
        [self.passwordField resignFirstResponder];
        [self loginAction];
    }
    
    return YES;
}

// 点击屏幕回收键盘
- (void)tapAction:(UITapGestureRecognizer *)sender {
    
    [self.userField resignFirstResponder];
    [self.passwordField resignFirstResponder];
}

- (void)leftAction {
    
    [self.delegate changeItem];
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}

@end
